package org.aplombh.java.utils.multiThread.juc.safe;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

public class Bank {
    public static void main(String[] args) {
        Account account = new Account(1000000, "marriage fund");
        Drawing i = new Drawing("I", account, 500000);
        Drawing girlfriend = new Drawing("Girlfriend", account, 1000000);
        i.start();
        girlfriend.start();
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Account {
    private int money;
    String name;
}

@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
class Drawing extends Thread {

    private Account account;
    private int withdrawalAmount;
    private int balance;

    public Drawing(String name, Account account, int withdrawalAmount) {
        super(name);
        this.account = account;
        this.withdrawalAmount = withdrawalAmount;
    }

    //Synchronize method, Default lock this
//    public synchronize void run(){}
    @Override
    public void run() {
        // Synchronize block,lock Object.
        synchronized (account){
            if (account.getMoney() - withdrawalAmount < 0) {
                System.out.println("Insufficient " + account.name + " balance," + Thread.currentThread().getName() + " didn't get any money.");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.setMoney(account.getMoney() - withdrawalAmount);
            balance = balance + withdrawalAmount;
            System.out.println(account.name + "'s bank balance is " + account.getMoney());
            System.out.println(this.getName() + " has " + balance + " left in hand");
        }
    }
}